<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>学生</title>
    <link rel="stylesheet" href="./bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="./bootstrap/bootstrap-icons.css" />
    <link rel="stylesheet" href="./css/common.css" />
    <link rel="stylesheet" href="./css/student.css" />
</head>

<body class="application application-offset">
    <div class="container-fluid container-application">
        <div class="sidenav show" id="sidenav-main">
            <!-- Sidenav header -->
            <div class="sidenav-header d-flex align-items-center">
                <a class="navbar-brand" href="./index.html">
                    <span class="logo">·ITCAST·</span>
                </a>
            </div>
            <!-- User mini profile -->
            <div class="sidenav-user d-flex flex-column align-items-center justify-content-between text-center">
                <!-- Avatar -->
                <div>
                    <a href="#" class="avatar rounded-circle avatar-xl">
                        <img alt="Image placeholder" src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg" class="" />
                    </a>
                    <div class="mt-5">
                        <h5 class="mb-0 text-white">黑马前端</h5>
                        <span class="d-block text-sm text-white opacity-8 mb-3">数据可视化</span>
                        <a href="javascript:;" class="btn btn-sm btn-white btn-icon rounded-pill shadow hover-translate-y-n3">
                            <span class="btn-inner--text">学前端来黑马</span>
                        </a>
                    </div>
                </div>
            </div>
            <!-- Application nav -->
            <div class="nav-application clearfix">
                <a href="./index.html" class="btn btn-square text-sm">
                    <span class="btn-inner--icon d-block"><i class="bi bi-house bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">首页</span>
                </a>
                <a href="./student.html" class="btn btn-square text-sm active">
                    <span class="btn-inner--icon d-block"><i class="bi bi-people bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">学生</span>
                </a>
                <a href="javascript:;" class="btn btn-square text-sm">
                    <span class="btn-inner--icon d-block"><i class="bi bi-columns bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">排版</span>
                </a>
                <a href="javascript:;" class="btn btn-square text-sm">
                    <span class="btn-inner--icon d-block"><i class="bi bi-files bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">资料</span>
                </a>
                <a href="javascript:;" class="btn btn-square text-sm">
                    <span class="btn-inner--icon d-block"><i class="bi bi-receipt bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">就业</span>
                </a>
                <a href="javascript:;" class="btn btn-square text-sm">
                    <span class="btn-inner--icon d-block"><i class="bi bi-gear bi-2x"></i></span>
                    <span class="btn-inner--icon d-block pt-2">设置</span>
                </a>
            </div>
            <!-- Misc area -->
            <div class="card bg-gradient-warning">
                <div class="card-body">
                    <h5 class="text-white">哈喽, 朋友!</h5>
                    <p class="text-white mb-4">为什么不现在开始学习前端，创造一些令人惊叹的东西呢？</p>
                    <a href="http://itcast.cn" class="btn btn-sm btn-block btn-white rounded-pill" target="_blank">Get started</a>
                </div>
            </div>
        </div>
        <div class="main-content position-relative">
            <nav class="navbar navbar-main navbar-expand-lg navbar-dark navbar-border" id="navbar-main">
                <div class="container-fluid">
                    <!-- Navbar nav -->
                    <div class="collapse navbar-collapse navbar-collapse-fade" id="navbar-main-collapse">
                        <ul class="navbar-nav align-items-lg-center">
                            <!-- Home  -->
                            <li class="nav-item">
                                <a class="nav-link pl-lg-0" href="./index.html"> 首页 </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link pl-lg-0" href="./index.html"> 传智教育 </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link pl-lg-0" href="./index.html"> 黑马程序员 </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link pl-lg-0" href="./index.html"> 文档 </a>
                            </li>
                        </ul>
                        <!-- Right menu -->
                        <ul class="navbar-nav ml-lg-auto align-items-center d-none d-lg-flex">
                            <li class="nav-item dropdown dropdown-animate">
                                <a class="nav-link pr-lg-0" href=".dropdown-menu" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <div class="media media-pill align-items-center">
                                        <span class="avatar rounded-circle">
                        <img alt="Image placeholder" src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg" />
                      </span>
                                        <div class="ml-2 d-none d-lg-block">
                                            <span class="mb-0 text-sm font-weight-bold">Admin</span>
                                        </div>
                                    </div>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link pl-lg-0" id="logout" href="javascript:;"> 退出 </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <div class="page-content">
                <div class="page-title mb-3">
                    <div class="row justify-content-between align-items-center">
                        <div class="col-md-6 mb-3 mb-md-0">
                            <h5 class="h3 font-weight-400 mb-0 text-white">Students</h5>
                            <span class="text-sm text-white opacity-8">一共有 <b class="total">0</b> 位学员</span>
                        </div>
                        <div class="col-md-6 d-flex align-items-center justify-content-between justify-content-md-end">
                            <a id="openModal" href="javascript:;" class="btn btn-sm btn-white btn-icon-only rounded-circle ml-4">
                                <span class="btn-inner--icon"><i class="bi bi-plus bi-2x"></i></span>
                            </a>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <div class="card card-fluid">
                            <div class="table-responsive" style="min-height: 1000px">
                                <table class="table align-items-center">
                                    <thead>
                                        <tr>
                                            <th>姓名</th>
                                            <th>年龄</th>
                                            <th>性别</th>
                                            <th>组号</th>
                                            <th>期望薪资</th>
                                            <th>就业薪资</th>
                                            <th>籍贯</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody class="list">
                                        <!-- <tr>
                      <td>张杰</td>
                      <td>20</td>
                      <td>男</td>
                      <td>第2组</td>
                      <td>10000</td>
                      <td>13000</td>
                      <td>北京北京市东城区</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr> -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- footer -->
                <div class="footer pt-5 pb-4 footer-light" id="footer-main">
                    <div class="row text-center text-sm-left align-items-sm-center">
                        <div class="col-sm-6">
                            <p class="text-sm mb-0">© 2022 <a href="https://itcast.cn" class="h6 text-sm" target="_blank">前端学科</a>. All rights reserved.</p>
                        </div>
                        <div class="col-sm-6 mb-md-0">
                            <ul class="nav justify-content-center justify-content-md-end">
                                <li class="nav-item">
                                    <a class="nav-link" href="#">Support</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#">Terms</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link pr-0" href="#">Privacy</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- add Modal -->
    <div class="modal fade" id="modal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加学员</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="form" class="g-3 row" autocomplete="off" novalidate>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">姓名：</label>
                                <input type="text" name="name" class="form-control" placeholder="请输入姓名" />
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">性别：</label>
                                <div class="input">
                                    <div class="form-check d-inline-block">
                                        <input value="0" checked id="cb01" class="form-check-input" type="radio" name="gender" />
                                        <label for="cb01" class="form-check-label">男</label>
                                    </div>
                                    <div class="form-check d-inline-block">
                                        <input value="1" id="cb02" class="form-check-input" type="radio" name="gender" />
                                        <label for="cb02" class="form-check-label">女</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">年龄：</label>
                                <input type="text" name="age" class="form-control" placeholder="请输入年龄" />
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">组号：</label>
                                <input type="text" name="group" class="form-control" placeholder="请输入1-8组号" />
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">期望薪资：</label>
                                <input type="text" name="hope_salary" class="form-control" placeholder="请输入期望薪资" />
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label class="input-group-label">就业薪资：</label>
                                <input type="text" name="salary" class="form-control" placeholder="请输入就业薪资" />
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <div class="form-group">
                                <label class="input-group-label">籍贯：</label>
                                <div class="input pl-0">
                                    <select class="form-select custom-select" name="province">
                      <option value="">--省份--</option>
                    </select>
                                    <select class="form-select custom-select" name="city">
                      <option value="">--城市--</option>
                    </select>
                                    <select class="form-select custom-select" name="area">
                      <option value="">--地区--</option>
                    </select>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-blue" id="submit">确认</button>
                </div>
            </div>
        </div>
    </div>
    <script src="./bootstrap/bootstrap.min.js"></script>
    <script src="./lib/axios.js"></script>
    <script src="./lib/form-serialize.js"></script>
    <script src="./js/common.js"></script>
    <script>
        //渲染功能 学生信息渲染
        //核心思路：
        //1.封装渲染函数
        //2.请求获取数据
        //3.基于数据，准备结构渲染
        //4.页面初始化调用

        //封装一个渲染函数 renderList
        async function renderList() {
            const res = await axios.get('/students')
            console.log(res) //查询学生列表成功
            document.querySelector('.table .list').innerHTML = res.data.map(item => {
                    return `
                    <tr>
                      <td>${item.name}</td>
                      <td>${item.age}</td>
                      <td>${item.gender === 0 ? '男':'女'}</td>
                      <td>第${item.group}组</td>
                      <td>${item.hope_salary}</td>
                      <td>${item.salary}</td>
                      <td>${item.province} ${item.city} ${item.area}</td>
                      <td>
        <a href="javascript:;" class="text-success mr-3"><i data-id="${item.id}" class="bi bi-pen"></i></a>
        <a href="javascript:;" class="text-danger"><i data-id="${item.id}" class="bi bi-trash"></i></a>
                      </td>
                    </tr>
                `
                }).join('')
                //渲染一共多少位学员
            document.querySelector('.total').innerHTML = res.data.length
        }
        renderList()

        //学生信息删除
        //核心思路：
        //1.事件委托绑定点击
        //2.渲染时绑定 id
        //3.点击获取绑定 id
        //4.调用删除接口
        //5.完成删除更新列表

        //删除或（编辑）功能（通过事件委托）
        document.querySelector('.list').addEventListener('click', async function(e) {
            //console.log(e.target)//当前点击的对象
            const btn = e.target
                //因为有两个按钮
                //判断当前点击的 i 按钮，有没有 bi-trash 的类，如果有，就是删除按钮
            if (btn.classList.contains('bi-trash')) {
                //获取要删除的 id
                const id = btn.dataset.id
                    //删除操作，发送删除请求，成功重新渲染
                try {
                    const res = await axios.delete(`/students/${id}`) //：id 需要在地址栏就要传id！！！
                        //console.log(res)//无返回数据
                        //重新渲染页面
                    renderList()
                } catch (e) {
                    console.dir(e)
                }
            }

            //点击编辑功能


            //判断当前点击的 i 按钮，有没有 bi-pen 的类，如果有，就是编辑按钮
            if (btn.classList.contains('bi-pen')) {
                modalBox.querySelector('.modal-title').innerHTML = '修改学员'
                    //将点击的编辑按钮的id，存到对话框上（对话框是唯一的，要改谁，就存谁的id）
                modalBox.dataset.id = btn.dataset.id

                //发送请求获取数据
                const {
                    data: student
                } = await axios.get(`/students/${modalBox.dataset.id}`)
                    //console.log(student) //查询学生详情成功
                    //遍历表单完成回显 获取表单里所有有name属性的表单元素
                    //伪数组转换为真数组
                    // [name] 表示所有 有 name 的表单属性的都获取！
                const fields = Array.from(modalBox.querySelectorAll('#form [name]'))
                fields.forEach(item => {
                    // item 表示所有有name属性的表单元素   

                    //处理性别回显
                    if (item.name === 'gender') {
                        //单选框要单独处理,两个单选框，不能都选中
                        // input.value === genger:1 (gender 是data里返回的数据)
                        // 看 input.value值和 student的gender值是否相等，相等才选中
                        if (+item.value === student.gender) {
                            item.checked = true
                        }
                    } else {
                        //input框，select框，都可以通过.value赋值
                        //item 就是每个有 name 属性的表单元素 （就是input输入框）
                        //item.name 就是每一项的name值
                        //利用 item.name 值，就可以去 student中用中括号语法去取值~
                        item.value = student[item.name]
                    }
                })


                // 处理省市区的回显
                //获取省的数据，渲染
                const {
                    data: province
                } = await axios.get('/api/province')
                const pStr = province.map(item => `<option value="${item}">${item}</option>`).join('')
                pSelect.innerHTML = `<option value="">--省份--</option>${pStr}`
                pSelect.value = student.province
                    //根据student.province(省)，要获取所有的市区，并且渲染市区，设置选中的是哪个城市
                const {
                    data: city
                } = await axios.get('/api/city', {
                    params: {
                        pname: pSelect.value
                    }
                })
                const cStr = city.map(item => `<option value="${item}">${item}</option>`).join('')
                cSelect.innerHTML = `<option value="">--城市--</option>${cStr}`
                cSelect.value = student.city
                    //根据student.city获取所有的地区，渲染地区，设置选中的是哪个地区
                const {
                    data: area
                } = await axios.get('/api/area', {
                    params: {
                        pname: pSelect.value,
                        cname: cSelect.value
                    }
                })
                const aStr = area.map(item => `<option value="${item}">${item}</option>`).join('')
                aSelect.innerHTML = `<option value="">--地区--</option>${aStr}`
                aSelect.value = student.area

                // 回显完成，显示弹框
                modal.show()
            }

        })


        //实现点击加号，弹框的显示
        const modalBox = document.querySelector('#modal')
        const modal = new bootstrap.Modal(modalBox) //创建实例


        document.querySelector('#openModal').addEventListener('click', () => {
            //1.重置表单
            document.querySelector('#form').reset()
                //2.设置标题
            document.querySelector('#modal .modal-title').innerHTML = '添加学员'
                //3.添加一个标识，将来区分到底是添加还是修改
                //如果是添加，记录一个字符串 "add"
                //如果是修改，记录一个修改的id
                //发现记录的值是字符串，说明是添加 否则是修改
            modalBox.dataset.id = 'add'
                //显示弹框
            modal.show()
        })


        const pSelect = document.querySelector('[name=province]') //省
        const cSelect = document.querySelector('[name=city]') //市
        const aSelect = document.querySelector('[name=area]') //区

        //初始化省市区联动的功能
        const initCity = async() => {
            //1.动态渲染省份
            //发送请求，组合结构，动态渲染
            const {
                data: province
            } = await axios.get('/api/province')
                //console.log(province) //数组，每一项是各个省的名称
                //把省的数据渲染到省的下拉框中
                //细节：option 标签value 属性记得设置值
            const pStr = province.map(item => `<option value="${item}">${item}</option>`).join('')
            pSelect.innerHTML = `<option value="">--省份--</option>${pStr}`

            //2.监听省份的选择
            //给省注册change 事件，省改变的时候触发
            pSelect.addEventListener('change', async() => {
                //console.log(pSelect.value) //当前省份

                aSelect.value = '' //重置区

                //动态渲染城市
                const {
                    data: city
                } = await axios.get('/api/city', {
                    params: {
                        pname: pSelect.value //根据当前省份来获取对应的城市
                    }
                })
                const cStr = city.map(item => `<option value="${item}">${item}</option>`).join('')
                cSelect.innerHTML = `<option value="">--城市--</option>${cStr}`
            })

            //3.监听城市的选择
            cSelect.addEventListener('change', async() => {
                //console.log(aSelect.value) //当前城市

                //动态渲染区
                const {
                    data: area
                } = await axios.get('/api/area', {
                    params: {
                        pname: pSelect.value,
                        cname: cSelect.value
                    }
                })
                const aStr = area.map(item => `<option value="${item}">${item}</option>`).join('')
                aSelect.innerHTML = `<option value="">--地区--</option>${aStr}`
            })

        }
        initCity()

        const form = modalBox.querySelector('form')
        const submitBtn = document.querySelector('#submit') //确认按钮

        submitBtn.addEventListener('click', async() => {
            //1.收集表单数据
            const data = serialize(form, {
                    hash: true
                })
                //console.log(data)
                //处理格式（后台部分数据需要number格式）
            data.age = +data.age
            data.gender = +data.gender
            data.hope_salary = +data.hope_salary
            data.salary = +data.salary
            data.group = +data.group
                //2.发送请求提交,做个判断
                //判断是否是添加操作，如果是，发送添加请求
            if (modalBox.dataset.id === 'add') {
                //添加操作
                try {
                    const res = await axios.post('/students', data)
                        //console.log(res)
                        //重新渲染页面
                    renderList()
                        //关闭弹窗
                    modal.hide()
                } catch (e) {
                    console.log(e)
                    alert('添加失败！')
                }
            } else {
                //修改操作

                //修改完成
                try {
                    await axios.put(`/students/${modalBox.dataset.id}`, data)
                    modal.hide()
                    renderList()
                } catch (error) {
                    alert('修改失败')
                }

            }
        })
    </script>
</body>

</html>